<template>
  <div class="paperEdit">
    <el-form ref="formRef" :model="form" label-width="auto" style="max-width: 600px" :rules="rules" f>
      <el-form-item label="年级:" prop="level">
        <el-select v-model="form.level" clearable @change="handleChange">
          <el-option label="一年级" :value="1" />
          <el-option label="二年级" :value="2" />
          <el-option label="三年级" :value="3" />
          <el-option label="四年级" :value="4" />
          <el-option label="五年级" :value="5" />
          <el-option label="六年级" :value="6" />
          <el-option label="初一" :value="7" />
          <el-option label="初二" :value="8" />
          <el-option label="初三" :value="9" />
          <el-option label="高一" :value="10" />
          <el-option label="高二" :value="11" />
          <el-option label="高三" :value="12" />
        </el-select>
      </el-form-item>

      <el-form-item label="学科:" prop="subjectId">
        <el-select v-model="form.subjectId">
          <el-option v-for="item in selectSubject" :key="item.id" :label="`${item.name}(${item.levelName})`"
            :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="试卷类型:" prop="paperType">
        <el-select v-model="form.paperType">
          <el-option label="固定试卷" value="1" />
          <el-option label="时段试卷" value="4" />
          <el-option label="任务试卷" value="6" />
        </el-select>
      </el-form-item>

      <el-form-item label="试卷名称:" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <template v-for="(item, index) in form.titleItems" :key="index">
        <el-form-item :label="`标题${index + 1}:`">
          <el-input v-model="item.name" style="width: 78%;" />
          <el-button type="primary" link @click="handleShow(index)">添加题目</el-button>
          <el-button type="primary" link @click="delTitle(index)">删除</el-button>
          <el-card style="width: 100%;">
            <p v-for="(question, idx) in item.questionItems">{{ idx + 1 }} 、 {{ question.title }}</p>
          </el-card>
        </el-form-item>
      </template>

      <el-form-item label="建议时长:" prop="suggestTime">
        <el-input v-model="form.suggestTime" placeholder="分钟" />
      </el-form-item>

      <el-form-item label="   ">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="success" @click="addTitle">添加标题</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="dialogVisible" width="60%">
      <QuestionList :subjectId="form.subjectId" @selectedIds="handleSelected" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import ExamAPI, { SubjectResponse, PaperParams, QuestionItem } from '@/api/system/exam.api'
import QuestionList from '@/components/QuestionList.vue';

const router = useRouter()
const route = useRoute()
const dialogVisible = ref(false)
let index = -1

let form = ref<PaperParams>({
  id: null, //试卷id
  level: null, //年级
  subjectId: null, //学科
  paperType: null, //试卷类型
  name: "",//试卷名称
  suggestTime: "", //考试时长
  limitDateTime: [], //限时
  titleItems: [],
  score: 0 //试卷总分
});

//获取表单实例
import type { ElForm } from 'element-plus'
const formRef = ref<InstanceType<typeof ElForm>>()

///////////////////////////////////////////////////////////////////////////////////
import type { FormRules } from 'element-plus'
//检查规则
const rules = reactive<FormRules<PaperParams>>({
  level: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  subjectId: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ],
  paperType: [
    { required: true, message: '请选择试卷类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入试卷名称', trigger: 'blur' }
  ],
  suggestTime: [
    { required: true, message: '请输入建议时长', trigger: 'blur' },
  ],

})

//初始化学科
const subjectData = ref<SubjectResponse[]>([])
const selectSubject = ref<SubjectResponse[]>([])
function getSubject() {
  ExamAPI.getSubject().then(res => {
    subjectData.value = res
    selectSubject.value = res
    // console.log(subjectData.value);
  })
}

//年级变化自动筛选可选学科
function handleChange(v: string | number | null | undefined) {
  form.value.subjectId = null
  if (v) {
    selectSubject.value = subjectData.value.filter(item => item.level == v)
  } else {
    selectSubject.value = [...subjectData.value]
  }
}


//信息初始化
function getList() {
  const queryId = route.query.id;
  form.value.id = Array.isArray(queryId) ? queryId[0] : queryId;

  if (form.value.id) {
    ExamAPI.searchPaperById(form.value.id).then(res => {
      // console.log(res);
      Object.assign(form.value, res);
    }
    )
  }
}

let ids: (number | string)[] = []
//接收子组件数据
function handleSelected(v: (string | number)[]) {
  ids = v
}

//提交前验证
const onSubmit = () => {
  // console.log('submit!')
  formRef.value?.validate((valid) => {
    if (valid) {
      ExamAPI.editExam(form.value).then(() => {
        ElMessage({
          message: '成功',
          type: 'success',
        })
        router.push('/user/administrator')
      })
    }
  })

}
//重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  form.value.id = null
  form.value.level = null
  form.value.subjectId = null
  form.value.paperType = null
  form.value.name = ""
  form.value.suggestTime = ""
  form.value.limitDateTime = []
  form.value.titleItems = []
  form.value.score = 0
};

//添加标题
function addTitle() {
  form.value.titleItems.push({
    name: "",
    questionItems: []
  })
}


//删除标题
function delTitle(index: number) {
  form.value.titleItems.splice(index, 1)
}

//打开题目列表
function handleShow(i: number) {
  if (form.value.subjectId) {
    index = i
    dialogVisible.value = true
  } else {
    ElMessage({
      type: "error",
      message: "请选择学科"
    })
  }
}
//题目列表的确认
function confirm() {
  let ps: any[] = []
  ids.forEach(item => [
    ps.push(ExamAPI.searchQuestionById(item))
  ])

  Promise.all(ps).then(res => {
    form.value.titleItems[index].questionItems = res
  })
  dialogVisible.value = false
}

onMounted(() => {
  resetForm()
  getSubject()
  getList()
})
</script>

<style scoped lang="scss">
.paperEdit {
  padding: 20px 40px;
}
</style>
